package com.bo.redis.limit;

/**
 * 令牌桶限流算法
 *
 * @Author: gpb
 * @Date: 2025/2/3 21:22
 * @Description:
 */
public class TokenBucketLimiter implements TrafficLimiter {
    // 令牌桶容量
    private int capacity = 100;
    // 令牌桶速率
    private int rate = 10;
    // 令牌桶中令牌数量
    private int tokens = 20;
    // 上次获取令牌时间
    private long lastTime = System.currentTimeMillis();

    @Override
    public boolean limit() {
        long now = System.currentTimeMillis();
        // 获取令牌数量，令牌最大为容量
        tokens = Math.min(capacity, tokens + (int) ((now - lastTime) * rate / 1000));
        lastTime = now;
        // 没有令牌了，限流
        if (tokens < 1) {
            return true;
        }
        tokens--;
        return false;
    }
}
